package com.finalterm.payment.controller;

import com.finalterm.common.result.Result;
import com.finalterm.payment.config.PaymentConfigProperties;
import com.finalterm.payment.service.PaymentTimeoutService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 支付配置管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/payment/config")
@RequiredArgsConstructor
public class PaymentConfigController {
    
    private final PaymentConfigProperties paymentConfig;
    private final PaymentTimeoutService paymentTimeoutService;
    
    /**
     * 获取当前支付超时配置
     */
    @GetMapping("/timeout")
    public Result<Integer> getPaymentTimeout() {
        Integer timeout = paymentTimeoutService.getPaymentTimeout();
        log.info("查询支付超时配置: {}秒", timeout);
        return Result.success("获取支付超时配置成功", timeout);
    }
    
    /**
     * 测试支付超时检测
     */
    @PostMapping("/timeout/test")
    public Result<String> testPaymentTimeout(@RequestParam(defaultValue = "2000") Long sleepMs) {
        long startTime = System.currentTimeMillis();
        
        try {
            log.info("开始测试支付超时，模拟处理时间: {}ms", sleepMs);
            Thread.sleep(sleepMs);
            
            boolean isTimeout = paymentTimeoutService.isPaymentTimeout(startTime);
            long remainingTime = paymentTimeoutService.getRemainingTimeout(startTime);
            
            String message = String.format("测试完成 - 是否超时: %s, 剩余时间: %dms", 
                    isTimeout ? "是" : "否", remainingTime);
            
            paymentTimeoutService.logPaymentDuration(startTime, !isTimeout);
            
            return Result.success(message);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Result.error("测试被中断");
        }
    }
    
    /**
     * 获取支付配置详情
     */
    @GetMapping("/details")
    public Result<PaymentConfigProperties> getPaymentConfig() {
        log.info("查询支付配置详情");
        return Result.success("获取支付配置成功", paymentConfig);
    }
}
